import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Organization } from './models/organization.entity';
import { DeepPartial, FindOptionsWhere, Repository } from 'typeorm';
// Repository是一个提供数据库操作的工具库
@Injectable()
export class OrganizationService {
  // 注入Organization实体
  constructor(
    @InjectRepository(Organization) private OrganizationRepository: Repository<Organization>,
  ) {}
  // 返回值是promise对象
  // DeepPartial是一个将实体（Organization）内部的所有属性加上?，即可以省略
  /**
   * 创建一个门店
   * @param entity 
   * @returns 
   */
  async create(entity: DeepPartial<Organization>): Promise<boolean> {
    // const res = await this.OrganizationRepository.insert(entity);//insert方法不会触发create事件
    const res = await this.OrganizationRepository.save(
      this.OrganizationRepository.create(entity), //create仅仅是创建一个内存实体，没有放入数据库
    ); //
    // console.log('res', res);
    if (res) {
      return true;
    }
    return false;
  }
  // 查询
  async findById(id: string): Promise<Organization | null> {
    const res = await this.OrganizationRepository.findOne({
      where: {
        id: id,
        // ...entity
      },
      relations:['orgFrontImg','orgRoomImg','orgOtherImg',]  //这里是关联表
    });
    // console.log('res', res);
    return res;
  }
  // 修改
  async updateById(id: string, entity: DeepPartial<Organization>): Promise<boolean> {
    const existEntity = await this.findById(id);
    if(!existEntity){
      return false
    }
    Object.assign(existEntity,entity)
    // const res = await this.OrganizationRepository.update(id, entity);//这里update方法是不会触发entity的update事件的
    const res = await this.OrganizationRepository.save(existEntity);//需要使用save
    if (res) {
      return true;
    }
    return false;
  }
  // 分页查询
  async findOrganizations({
    start,
    size,
    where,
  }: {
    start: number;
    size: number;
    where: FindOptionsWhere<Organization>;
  }): Promise<[Organization[], number]> {
    const res = this.OrganizationRepository.findAndCount({
      take: size,
      skip: start,
      where,
      order: {
        createAt: 'DESC',
      },
      relations:['orgFrontImg','orgRoomImg','orgOtherImg',]  //这里是关联表
    });
    return res;
  }

  // 软删除
  async deleteById(id: string,userId:string): Promise<boolean> {
    const res1 = await this.OrganizationRepository.update(id,{
      deleteBy:userId,
    });
    // console.log('res', res);
    if (res1) {
      const res = await this.OrganizationRepository.softDelete(id);
      if(res?.affected > 0){
        return true;
      }
    }
    return false;
  }
}
